package com.tarena.demo.luban.all.main.service.impl;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.tarena.demo.luban.all.main.mapper.OrderMapper;
import com.tarena.demo.luban.all.main.service.OrderService;
import com.tarena.demo.luban.protocol.cart.param.CartDeleteParam;
import com.tarena.demo.luban.protocol.order.dos.OrderDO;
import com.tarena.demo.luban.protocol.order.param.OrderAddParam;
import com.tarena.demo.luban.protocol.stock.param.StockReduceCountParam;
import com.tarena.luban.demo.cart.api.CartApi;
import com.tarena.luban.demo.cart.api.CartTestApi;
import com.tarena.luban.demo.stock.api.StockApi;
import org.apache.dubbo.config.bootstrap.DubboBootstrap;
import org.apache.dubbo.rpc.RpcContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.Future;

@Service
public class OrderServiceImpl implements OrderService {
    /*@Autowired
    private CartService cartService;
    @Autowired
    private StockService stockService;*/
    @Autowired
    private OrderMapper orderMapper;
    @Autowired(required = false)
    private CartApi cartApi;
    @Autowired(required = false)
    private StockApi stockApi;
    @Autowired(required = false)
    private CartTestApi cartTestApi;
    @Override public void addOrder(OrderAddParam param) {
        //全局唯一值
        String orderSn=param.getOrderSn();
        long total=orderMapper.countOrderByOrderSn(orderSn);
        if (total>0){
            //已经存在这个orderSn的订单了
            return;
        }
        //减库存
        StockReduceCountParam stockReduceCountParam=new StockReduceCountParam();
        stockReduceCountParam.setReduceCount(param.getCount());
        stockReduceCountParam.setProductCode(param.getProductCode());
        stockReduceCountParam.setOrderSn(param.getOrderSn());
        stockApi.reduceCount(stockReduceCountParam);
        //增订单
        OrderDO orderDO=new OrderDO();
        BeanUtils.copyProperties(param,orderDO);
        orderMapper.insertOrder(orderDO);
        //删除购物车
        Entry entry=null;
        try {
            entry= SphU.entry("orderCartDelete");
            CartDeleteParam cartDeleteParam = new CartDeleteParam();
            cartDeleteParam.setUserId(param.getUserId());
            cartDeleteParam.setProductCode(param.getProductCode());
            System.out.println("当前cartApi 类型:" + cartApi.getClass().getName());
            Boolean result = cartApi.deleteCart(cartDeleteParam);
        }catch (BlockException e){
            //熔断降级
            //记录一个日志 /发送一个消息 表示该订单的购物车没删除
            System.out.println("当前购物车删除失败:order:"+param);
        }finally {
            if (entry!=null)entry.exit();
        }
    }

}
